#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <libmedia/video_frame.h>

#include "photo_jpeg.h"
#include "debug/debug.h"

#include "media.h"

int media_photo_frame(const char* record_dir, const char * name, struct video_frame* frame)
{
    int ret = -1;
    struct hw_jpeg_video_encoder_param jpeg_param;
    struct video_encoder* video_encoder = NULL;
    struct media_packet* jpeg_pkt = NULL;
    struct tm* t = NULL;
    FILE* jpeg_file = NULL;
    char file_name[MAX_RECORD_FILE_NAME_LENGHT] = { 0 };
	char mkdir_cmd[100] = "mkdir ";

	strcat(mkdir_cmd, record_dir);
	strcat(mkdir_cmd, " -p");

	time_t cur_time;
 	time(&cur_time);
 	t = localtime(&cur_time);

    sprintf(file_name, "%s/%s", record_dir, name);
	system(mkdir_cmd);

    jpeg_file = fopen(file_name, "wb");
    if (jpeg_file == NULL)
    {
        print_error("open %s faild in the path:%s!", name, record_dir);
        return ret;
    }
    
    hw_jpeg_encoder_init_default_param(&jpeg_param, frame->width, frame->height);
    video_encoder = video_encoder_open(&jpeg_param.param);
    assert(video_encoder);

    video_encoder_write_frame(video_encoder, frame);
    video_encoder_get_packet(video_encoder, &jpeg_pkt);

    fwrite(jpeg_pkt->data, jpeg_pkt->size, 1, jpeg_file);
    fclose(jpeg_file);
    media_packet_put(jpeg_pkt);

    video_encoder_close(video_encoder);

    print_debug("take a picture %s.", file_name);

    return 0;

}


